import {Table,Icon,Row,Col,Button,Spin,Modal} from 'antd'
const confirm = Modal.confirm;
import {WeaTools,WeaInput,WeaSelect,WeaBrowser,WeaDatePicker,WeaCheckbox} from 'ecCom'
import './style/index.css'
import equal from "deep-equal"

class WeaCrmTableEdit extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			columns: [],
			datas: [],
			selectedRowKeys: [],
			current: 1,
			showGroup: props.showGroup ? props.showGroup : false
		}
		this.onEdit = this.onEdit.bind(this);
		this.doCopy = this.doCopy.bind(this);
		this.doDelete = this.doDelete.bind(this);
		this.doAdd = this.doAdd.bind(this);
	}
	componentDidMount() {
		const { datas = [], columns = [] } = this.props;
		columns.length > 0 && this.setState(datas.length > 0 ? {datas: this.addKeytoDatas(datas),columns} : {columns})
	}
	componentWillReceiveProps(nextProps,nextState) {
		const { columns = [], datas = [], selectedRowKeys = [] } = this.props;
		const _columns = nextProps.columns || [];
		const _datas = nextProps.datas || [];
		const _selectedRowKeys = nextProps.selectedRowKeys || [];
		!equal(columns,_columns) && this.setState({columns});
		!equal(datas,_datas) && this.setState({datas: this.addKeytoDatas(_datas)});
		!equal(selectedRowKeys,_selectedRowKeys) && this.setState({selectedRowKeys})
	}
	componentDidUpdate() {
		
	}
	addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
	render() {
		const { datas,showGroup,columns, selectedRowKeys } = this.state;
		const {title,needAdd,needCopy} = this.props;
		return(
			<div className="wea-crm-table-edit" >
				<Row className="wea-title">
                    <Col span="20">
                        <div>{title}</div>
                    </Col>
					<Col span="4" style={{textAlign:"right",paddingRight:10,fontSize:12}}>
						{needAdd &&	
							<span>
								<Button type="primary" title='新增' size="small" onClick={this.doAdd}><Icon type="plus" /></Button>
								<Button type="primary" disabled={!`${selectedRowKeys}`} title='删除' size="small" onClick={this.doDelete} ><Icon type="minus" /></Button>
							</span>
						}	
						{needCopy && 
							<Button type="primary" disabled={!`${selectedRowKeys}`} title='复制' size="small" onClick={this.doCopy} ><Icon type="copy" /></Button>
						}
						<Icon type={showGroup ? 'up' : 'down'} onClick={()=>this.setState({showGroup:!showGroup})}/>
	                </Col>
                </Row>
				<Row className="wea-content" style={{display:showGroup ? "block":"none"} }>
					<Col className="wea-form-cell" span={24}>
						<Table 
							columns={this.getColumns()}
							dataSource={datas}
							pagination={false}
							rowSelection={this.getRowSelection()}
						/>
					 </Col>
                </Row>
               
            </div>
		)
	}
	getColumns(){
		const { columns } = this.state;
		let _columns = [].concat(columns);
		_columns = _columns.map(col => {
			let _col = { ...col };
			_col.render = ( text, record, index ) => {
				return this.getColRender( _col, text, record, index );
			}
			return _col
		});
		return _columns
	}
	getColRender( _col, text, record, index ){
		const { com,isLink = false,linkKey =[],linkUrl=""} = _col;
		let _com = [];
		com.map(c => {
			if(typeof c.props === 'object'){
				_com.push(c);
			}else{
				const { domkey,viewAttr =2,  formItemType = 'INPUT', options = [], browserConditionParam = {}, width ,value } = c;
				const _type = formItemType.toUpperCase();
				_com.push(
					<span>
						{ _type === 'INPUT' && !isLink && 
							<WeaInput 
								 defaultValue={value || ""} 
								value={record[domkey[0]]} 
								style={{width, display: 'inline-block'}}
								onBlur={value => this.onEdit(record, index, domkey[0], value)}
								viewAttr={viewAttr} /> 
						}
						{ _type === 'INPUT' && isLink && 
							<WeaInput 
								 defaultValue={record[domkey[0]]} 
								value={record[domkey[0]]} 
								style={{width, display: 'inline-block'}}
								onBlur={value => this.onInptEdit(record, index, domkey[0], value,"",linkKey)}
								viewAttr={viewAttr} 
								type={"number"}/> 
						}
						{ _type === 'BROWSER' && !isLink && 
							<WeaBrowser 
								replaceDatas={this.getBrowerDatas(record, domkey[0])}
								{...browserConditionParam}
								style={{width, display: 'inline-block'}}
								onChange={(ids, names, bDatas) => this.onEdit(record, index, domkey[0], ids, names, bDatas)}
							/> 
						}
						{ _type === 'BROWSER' && isLink && 
							<WeaBrowser 
								replaceDatas={this.getBrowerDatas(record, domkey[0])}
								{...browserConditionParam}
								style={{width, display: 'inline-block'}}
								onChange={(ids, names, bDatas) => this.onLinkEdit(record, index, domkey[0], ids, names, bDatas,linkUrl,linkKey)}
								 /> 
						}
						{ _type === 'DATEPICKER' && 
							<WeaDatePicker
								value={record[domkey[0]]} 
								style={{width, display: 'inline-block'}}
								formatPattern={2}
								viewAttr={viewAttr}
								onChange={value => this.onEdit(record, index, domkey[0], value)}
							/>
						}
						{ _type === 'CHECKBOX' &&  
							<WeaCheckbox
								value={record[domkey[0]]=="1"? true:false} 
								style={{width, display: 'inline-block'}}
								viewAttr={viewAttr}
								onChange={value => this.onEdit(record, index, domkey[0], value)}
							/>
						}
						{ _type === 'SELECT' && isLink && 
							<WeaSelect
								value={record[domkey[0]]} 
								style={{width, display: 'inline-block'}}
								options= {options}
								viewAttr={viewAttr}
								hasBorder
								onChange={value => this.onSelectEdit(record, index, domkey[0], value,"",linkKey)}
							/>
						}
					</span>
				)
			}
		});
		return (
			<div>
				{_com}
			</div>
		)
	}
	getBrowerDatas(record, key){
		let replaceDatas = [];
		if(record[key + 'span'] !== undefined) {
			let keys = record[key].split(',');
			let values = record[key + 'span'].split(',');
			if(keys.length === values.length){
				keys.map((k, i) => {
					replaceDatas.push({id: k, name: values[i]});
				});
			}else{
				console.log('浏览按钮数据有误！！，显示名中不能包含有英文逗号" , "');
			}
		}
		return replaceDatas
	}
	getRowSelection(){
		const { columns, selectedRowKeys } = this.state;
		if(!`${columns}`) return null
		const rowSelection = {
			selectedRowKeys,
			onChange: (sRowKeys, selectedRows) => {
				this.setState({selectedRowKeys : sRowKeys});
				typeof this.props.onRowSelect === 'function' && this.props.onRowSelect(sRowKeys);
			}
		}
		return rowSelection
	}
	onEdit(record, index, key, value, names, bDatas){
		const { pageSize = 0 } = this.props;
		const { datas, current } = this.state;
		let _datas = [].concat(datas);
		_datas[pageSize * (current - 1) + index][key] = value;
		if(names) _datas[pageSize * (current - 1) + index][key + 'span'] = names;
		this.setState({datas: _datas});
		this.onChange(_datas);
	}

	onLinkEdit(record, index, key, value, names, bDatas,linkUrl,linkKey){
		const that = this;
		const { pageSize = 0 } = this.props;
		const { datas, current } = this.state;
		let _datas = [].concat(datas);
		_datas[index][key] = value;
		if(names) _datas[index][key + 'span'] = names;
		return WeaTools.callApi('/api/crm/product/productInfo', 'GET', {productId:value}).then(({datas}) => {		
			_datas[index][linkKey[0]] = datas.assetunitid;	
			if(names) _datas[index][linkKey[0] + 'span'] = datas.assetunitname;
			if(linkKey[1]){_datas[index][linkKey[1]] =datas.salesprice } 

			that.setState({datas: _datas});
			that.onChange(_datas);
		});
	}
	onInptEdit(record, index, key, value, names,linkKey){
		const { pageSize = 0 } = this.props;
		const { datas, current } = this.state;
		let _datas = [].concat(datas);
		_datas[pageSize * (current - 1) + index][key] = value;
		if(_datas[index][linkKey[0]]) 
			_datas[index][linkKey[1]] = Number(value)* Number(_datas[index][linkKey[0]] ||0);

		if(_datas[index][linkKey[2]]){ 
			_datas[index][linkKey[1]] = Number(value)* Number(_datas[index][linkKey[0]]||0)* Number(_datas[index][linkKey[2]]||0);
		}
		this.setState({datas: _datas});
		this.onChange(_datas);
	}
	onSelectEdit(record, index, key, value, names,linkKey){
		const { datas } = this.state;
		let _datas = [].concat(datas);
		const that = this;
		confirm({
			title: '付款性质已变，是否清空预算科目？',
			content: '',
			onOk() {
				_datas[index][key] = value;
				if(_datas[index][linkKey[0]]) {
					_datas[index][linkKey[0]] = "";
					_datas[index][linkKey[0] + 'span'] = "";
				}
				that.setState({datas: _datas});
				that.onChange(_datas);
			},
			onCancel() {},
		  });
	}
	doCopy(){
		const { datas, current, selectedRowKeys } = this.state;
		let _datas = [].concat(datas);
		selectedRowKeys.map(key => {
			datas.map(data => {
				if(data.key == key){
					let _data = {...data};
					_data.key = _datas.length;
					_datas.push(_data)
				}
			})
		});
		this.setState({datas: _datas});
		this.onChange(_datas);
	}
	doAdd(){
		const { datas } = this.state;
		let _datas = [].concat(datas);
		let _data = {...datas[0]};
		for(let k in _data){
			_data[k] = ''
		}
		_data.key = _datas.length;
		_datas.push(_data);
		this.setState({datas: _datas});
		this.onChange(_datas);
	}
	doDelete(){
		const { datas, current, selectedRowKeys } = this.state;
		let _datas = [].concat(datas);
		selectedRowKeys.map(key => {
			_datas = _datas.filter(data => data.key !== key)
		});
		_datas = _datas.map((data, i) => {
			let _data = {...data};
			_data.key = i;
			return _data
		})
		this.setState({datas: _datas,selectedRowKeys: []});
		this.onChange(_datas);
		
	}
	onChange(datas){
		const { columns } = this.state;
		let _datas = datas.map((data, i) => {
			let _data = {...data}
			delete _data.key
			return _data
		})
		typeof this.props.onChange === 'function' && this.props.onChange(_datas, columns);
	}
}

export default WeaCrmTableEdit;
